var fs      = require('fs'),
    path    = require('path'),
    http    = require('http'),
    https   = require('https'),
    mime    = require('mime'),
    deflate = require('permessage-deflate'),
    faye    = require('faye');


var bayeux     = new faye.NodeAdapter({mount: '/', timeout: 20}),
    port       = process.argv[2] || '8000',
    secure     = process.argv[3] === 'tls',
    key        = fs.readFileSync(__dirname + '/server.key'),
    cert       = fs.readFileSync(__dirname + '/server.crt');
    _msg       = null;
    special    = '/special';


bayeux.addWebsocketExtension(deflate);
var server = secure ? https.createServer({cert: cert, key: key}) : http.createServer();

bayeux.attach(server);
server.listen(Number(port));


bayeux.getClient().subscribe(special, function(message) {
  console.log('Subscribe/Save /special message:' + message.title);
  _msg = message;
});

bayeux.on('subscribe', function(clientId, channel) {
  console.log('Subscribe ' + clientId + ' -> ' + channel);
  
 
  if (channel == special && _msg != null) {
    console.log('Send message to ' + clientId + ' -> ' + channel);
    
    var client = new faye.Client((secure ? 'https' : 'http') + '://localhost:' + port + '/');
    client.publish(special, _msg, {attempts: 1});
  }
});

bayeux.on('unsubscribe', function(clientId, channel) {
  console.log('Unsubscribe ' + clientId + ' -> ' + channel);
  
  if (channel == special)
    _msg = null;
});

bayeux.on('disconnect', function(clientId) {
  //console.log('Disconnect ' + clientId);
});

console.log('Listening on ' + port + (secure? ' (https)' : ''));
